package com.wondersgroup.robot.web.action;

import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.hibernate.Transaction;
import org.mira.lucene.analysis.IK_CAnalyzer;

import com.wondersgroup.robot.common.Nehnre;
import com.wondersgroup.robot.dao.RoKeyDAO;
import com.wondersgroup.robot.dao.RoQuestionDAO;
import com.wondersgroup.robot.dao.RoQuestionKeyDAO;
import com.wondersgroup.robot.po.RoKey;
import com.wondersgroup.robot.po.RoQuestion;
import com.wondersgroup.robot.po.RoQuestionKey;

/**
 * 
 * @author nehnre
 *
 */
public class Chat {
	private static final int MAX_SENTENCE_LENGTH = 200;
	/**
	 * 分词
	 * @param sentence
	 * @return
	 * @throws Exception
	 */
    public String splitWord(String sentence) throws Exception {
		if (StringUtils.isNotEmpty(sentence)) {
			sentence = sentence.replaceAll("<[^>]*>|&[^;]*;", "");
			if(sentence.length() > MAX_SENTENCE_LENGTH){
				sentence = sentence.substring(0,MAX_SENTENCE_LENGTH);
			}
			Analyzer analyzer = new IK_CAnalyzer();
			Reader r = new StringReader(sentence);
			TokenStream ts = (TokenStream) analyzer.tokenStream("", r);
			Token t;
			StringBuffer sb = new StringBuffer();
			while ((t = ts.next()) != null) {
				sb.append(t.termText());
				sb.append(",");
			}
			return sb.toString();
		}
		return "";
	}
    /**
     * 保存进数据库，并启动线程进行分词操作
     * @param title
     * @param content
     */
    public void initQuestion(String question, String answer){
    	RoQuestionDAO dao = new RoQuestionDAO();
    	RoQuestion rq = new RoQuestion();
    	rq.setRoquQuestion(question);
    	rq.setRoquAnswer(answer);
    	rq.setRoquCreateTime(new Date());
    	rq.setRoquLastChangeTime(new Date());
    	Transaction tx = dao.getSession().beginTransaction();
    	dao.save(rq);
    	tx.commit();
    	SplitQuestion sq = new SplitQuestion(rq.getRoquId(),question,answer);
    	Thread td = new Thread(sq);
    	td.start();
    }
    
    public String findBestAnswer(HttpServletRequest request, HttpServletResponse response) throws Exception{
    	String content = request.getParameter("content");
    	JSONObject result;
    	
    	content = Nehnre.decode(content);
    	JSONObject jsonKeyNum = splitWord(content, true);
    	
    	//根据jsonKeyNum生成结果集
    	result = generateResult(jsonKeyNum);
    	
    	//找出问题的答案
    	JSONArray arr = findQuestionByResult(result);
    	
    	return "["+arr.toString()+","+jsonKeyNum.toString()+"]";
    }
    /**
     * 
     * @param jsonKeyNum
     * @return
     */
	private JSONObject generateResult( JSONObject jsonKeyNum) {
		RoKeyDAO rkd = new RoKeyDAO();
		JSONObject result = new JSONObject();
		Iterator itKeys = jsonKeyNum.keys();
    	while(itKeys.hasNext()){
    		String key = (String)itKeys.next();
    		List list = rkd.findByProperty("rokeKey", key);
    		if(list.size() > 0){
    			RoKey rk = (RoKey)list.get(0);
    			RoQuestionKeyDAO rqkd = new RoQuestionKeyDAO();
    			List dbKeys = rqkd.findByProperty("id.rokeId", rk.getRokeId());
    			result = findQuestionIdByKeys(result, dbKeys, jsonKeyNum.getInt(key));
    		}
    	}
    	return result;
	}

	/**
	 * 
	 * @param dbKeys
	 * @return
	 */
	private JSONObject findQuestionIdByKeys(JSONObject result, List dbKeys, int keyNum) {
		
		for(int i=0;i<dbKeys.size();i++){
			RoQuestionKey rqk = (RoQuestionKey)dbKeys.get(i);
			String roquId = rqk.getId().getRoquId();
			int roqkCount = rqk.getRoqkCount().intValue() * keyNum;
			if(result.containsKey(roquId)){
				int j = result.getInt(roquId);
				result.remove(roquId);
				result.accumulate(roquId, j + roqkCount);
			} else {
				result.accumulate(roquId, roqkCount);
			}
		}
		return result;
	}
	/**
	 * @param result
	 * @return
	 */
	private JSONArray findQuestionByResult(JSONObject result) {
		RoQuestionDAO rqd = new RoQuestionDAO();
    	Iterator itIds = result.keys();
    	JSONObject json ;
    	JSONArray jsonArr = new JSONArray();
    	List list = new ArrayList();
    	while(itIds.hasNext()){
    		String id = (String)itIds.next();
    		RoQuestion rq = rqd.findById(id);
    		json = new JSONObject();
    		json.accumulate("question", rq.getRoquQuestion());
    		json.accumulate("answer", rq.getRoquAnswer());
    		json.accumulate("count", result.get(id));
    		list.add(json);
    	}
    	Object[] arr = list.toArray();
    	Arrays.sort(arr,new Comparator(){
			public int compare(Object arg0, Object arg1) {
				return ((JSONObject)arg1).getInt("count") - ((JSONObject)arg0).getInt("count");
			}
    	});
    	for(int i=0;i<arr.length;i++){
    		jsonArr.add(arr[i].toString());
    	}
		return jsonArr;
	}
    public JSONObject splitWord(String sentence, boolean b) throws Exception {
    	JSONObject json = new JSONObject();
		if (StringUtils.isNotEmpty(sentence)) {
			sentence = sentence.replaceAll("<[^>]*>|&[^;]*;", "");
			Analyzer analyzer = new IK_CAnalyzer();
			Reader r = new StringReader(sentence);
			TokenStream ts = (TokenStream) analyzer.tokenStream("", r);
			Token t;
			while ((t = ts.next()) != null) {
				String termText = t.termText();
				if(json.containsKey(termText)){
					int i = json.getInt(termText);
					json.remove(termText);
					json.accumulate(termText, i + 1);
				} else {
					json.accumulate(termText, 1);
				}
			}
		}
		return json;
	}
    public static void main(String args[]){
    	try {
			//new Chat().findBestAnswer();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}
